{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "tutorial.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "67gUU740MSXd",
        "colab_type": "text"
      },
      "source": [
        "# Tutorial\n",
        "\n",
        "This tutorial will teach the basics of how to use cirq.  This tutorial will walk through how to use qubits, gates, and operations to create and simulate your first quantum circuit using cirq.  It will briefly introduce devices, unitary matrices, decompositions, and optimizers.\n",
        "\n",
        "Note that this tutorial isn’t a quantum computing 101 tutorial, we assume familiarity of quantum computing at about the level of the textbook “Quantum Computation and Quantum Information” by Nielsen and Chuang.\n",
        "\n",
        "For more in-depth examples closer to those found in current work, check out our tutorials page."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1dOjJlgrNUuz",
        "colab_type": "text"
      },
      "source": [
        "To begin, please follow the instructions for [installing Cirq](install.md)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zVJYIBGjL8TT",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!pip install cirq --quiet"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xr-MMoXgNsUQ",
        "colab_type": "text"
      },
      "source": [
        "## Qubits\n",
        "\n",
        "The first part of creating a quantum circuit is to define a set of qubits (also known as a quantum registers) to act on.\n",
        "\n",
        "Cirq has three main ways of defining qubits:\n",
        "\n",
        "*   `cirq.NamedQubit`: used to label qubits by an abstract name\n",
        "*   `cirq.LineQubit`: qubits labelled by number in a linear array \n",
        "*   `cirq.GridQubit`: qubits labelled by two numbers in a rectangular lattice.\n",
        "\n",
        "Here are some examples of defining each type of qubit."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "PsgSo-H0Os8X",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import cirq\n",
        "\n",
        "# Using named qubits can be useful for abstract algorithms\n",
        "# as well as algorithms not yet mapped onto hardware.\n",
        "q0 = cirq.NamedQubit('source')\n",
        "q1 = cirq.NamedQubit('target')\n",
        "\n",
        "# Line qubits can be created individually\n",
        "q3 = cirq.LineQubit(3)\n",
        "\n",
        "# Or created in a range\n",
        "# This will create LineQubit(0), LineQubit(1), LineQubit(2)\n",
        "q0, q1, q2 = cirq.LineQubit.range(3)\n",
        "\n",
        "# Grid Qubits can also be referenced individually\n",
        "q4_5 = cirq.GridQubit(4,5)\n",
        "\n",
        "# Or created in bulk in a square\n",
        "# This will create 16 qubits from (0,0) to (3,3)\n",
        "qubits = cirq.GridQubit.square(4)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4zE6AutyQhQ6",
        "colab_type": "text"
      },
      "source": [
        "There are also pre-packaged sets of qubits called [Devices](devices.md).  These are qubits along with a set of rules of how they can be used.  A `cirq.Device` can be used to apply adjacency rules and other hardware constraints to a quantum circuit.  For our example, we will use the `cirq.google.Foxtail` device that comes with cirq.  It is a 2x11 grid that mimics early hardware released by Google."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "B0Dwgu-lQLpq",
        "colab_type": "code",
        "outputId": "8ddb536a-86d6-40bf-a98c-f4fc77424bc6",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85
        }
      },
      "source": [
        "print(cirq.google.Foxtail)"
      ],
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10)\n",
            "│        │        │        │        │        │        │        │        │        │        │\n",
            "│        │        │        │        │        │        │        │        │        │        │\n",
            "(1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "j1QTjyxLSe5c",
        "colab_type": "text"
      },
      "source": [
        "## Gates and Operations\n",
        "\n",
        "The next step is to use the qubits to create operations that can be used in our circuit.  Cirq has two concepts that are important to understand here:\n",
        "\n",
        "*   A `Gate` is an effect that can be applied to a set of qubits.  \n",
        "*   An `Operation` is a gate applied to a set of qubits.\n",
        "\n",
        "For instance, `cirq.H` is the quantum [Hadamard](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) and is a `Gate` object.  `cirq.H(cirq.LineQubit(1))` is an `Operation` object and is the Hadamard gate applied to a specific qubit (line qubit number 1).\n",
        "\n",
        "Many textbook gates are included within cirq.  `cirq.X`, `cirq.Y`, and `cirq.Z` refer to the single-qubit Pauli gates.  `cirq.CZ`, `cirq.CNOT`, `cirq.SWAP` are a few of the common two-qubit gates.  `cirq.measure` is a macro to apply a `MeasurementGate` to a set of qubits.  You can find more, as well as instructions on how to creats your own custom gates, on the [Gates documentation](gates.ipynb) page.\n",
        "\n",
        "Many arithmetic operations can also be applied to gates.  Here are some examples:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wDW-yU-fesDl",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# Example gates\n",
        "not_gate = cirq.CNOT\n",
        "pauli_z = cirq.Z\n",
        "\n",
        "# Using exponentiation to get square root gates\n",
        "sqrt_x_gate = cirq.X**0.5\n",
        "sqrt_iswap = cirq.ISWAP**0.5\n",
        "\n",
        "# Some gates can also take parameters\n",
        "sqrt_sqrt_y = cirq.YPowGate(exponent=0.25)\n",
        "\n",
        "# Example operations\n",
        "q0, q1 = cirq.LineQubit.range(2)\n",
        "z_op = cirq.Z(q0)\n",
        "not_op = cirq.CNOT(q0, q1)\n",
        "sqrt_iswap_op = sqrt_iswap(q0, q1)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BnBGLMVvWVkz",
        "colab_type": "text"
      },
      "source": [
        "## Circuits and Moments\n",
        "\n",
        "We are now ready to construct a quantum circuit.  A `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice.  Each `Operation` must have a disjoint set of qubits from the other `Operation`s in the `Moment`.  A `Moment` can be thought of as a vertical slice of a quantum circuit diagram.\n",
        "\n",
        "Circuits can be constructed in several different ways.  By default, cirq will attempt to slide your operation into the earliest possible `Moment` when you insert it.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "HEuqEZcXkz3Q",
        "colab_type": "code",
        "outputId": "dbb11050-0c9b-4356-a1ef-bb8014e4a695",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "circuit = cirq.Circuit()\n",
        "# You can create a circuit by appending to it\n",
        "circuit.append(cirq.H(q) for q in cirq.LineQubit.range(3))\n",
        "# All of the gates are put into the same Moment since none overlap\n",
        "print(circuit)"
      ],
      "execution_count": 58,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0: ───H───\n",
            "\n",
            "1: ───H───\n",
            "\n",
            "2: ───H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Lbez4guQl31P",
        "colab_type": "code",
        "outputId": "d1d7b32c-98cb-4881-a19c-92aeeb15a16b",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 136
        }
      },
      "source": [
        "# We can also create a circuit directly as well:\n",
        "print(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3)))"
      ],
      "execution_count": 59,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0: ───×───────────\n",
            "      │\n",
            "1: ───×───×───────\n",
            "          │\n",
            "2: ───────×───×───\n",
            "              │\n",
            "3: ───────────×───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3FC9bdlXmShh",
        "colab_type": "text"
      },
      "source": [
        "Sometimes, you may not want cirq to automatically shift operations all the way to the left.  To construct a circuit without doing this, you can create the circuit moment-by-moment or use a different `InsertStrategy`, explained more in the [Circuit documentation](circuits.ipynb)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4AEahodTnYiI",
        "colab_type": "code",
        "outputId": "5f878981-1600-45fd-a2ec-7f3f265a5a03",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        }
      },
      "source": [
        "# Creates each gate in a separate moment.\n",
        "print(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3)))"
      ],
      "execution_count": 60,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0: ───H───────────\n",
            "\n",
            "1: ───────H───────\n",
            "\n",
            "2: ───────────H───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "j406AKYsobpq",
        "colab_type": "text"
      },
      "source": [
        "### Circuits and Devices\n",
        "\n",
        "One important comnsideration when using real quantum devices is that there are often hardware constraints on the circuit.  Creating a circuit with a `Device` will allow you to capture some of these requirements.  These `Device` objects will validate the operations you add to the circuit to make sure that no illegal operations are added.\n",
        "\n",
        "Let's look at an example using the Foxtail device."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9UV-dXJOpy8B",
        "colab_type": "code",
        "outputId": "0e162827-2c42-4ade-e221-d2fdca93dcb6",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 170
        }
      },
      "source": [
        "q0 = cirq.GridQubit(0, 0)\n",
        "q1 = cirq.GridQubit(0, 1)\n",
        "q2 = cirq.GridQubit(0, 2)\n",
        "adjacent_op = cirq.CZ(q0, q1)\n",
        "nonadjacent_op = cirq.CZ(q0, q2)\n",
        "\n",
        "# This is an unconstrained circuit with no device\n",
        "free_circuit = cirq.Circuit()\n",
        "# Both operations are allowed:\n",
        "free_circuit.append(adjacent_op)\n",
        "free_circuit.append(nonadjacent_op)\n",
        "print('Unconstrained device:')\n",
        "print(free_circuit)\n",
        "print()\n",
        "\n",
        "# This is a circuit on the Foxtail device\n",
        "# only adjacent operations are allowed.\n",
        "print('Foxtail device:')\n",
        "foxtail_circuit = cirq.Circuit(device=cirq.google.Foxtail)\n",
        "foxtail_circuit.append(adjacent_op)\n",
        "try:\n",
        "  # Not allowed, will throw exception\n",
        "  foxtail_circuit.append(nonadjacent_op)\n",
        "except ValueError as e:\n",
        "  print('Not allowed. %s' % e)\n"
      ],
      "execution_count": 61,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Unconstrained device:\n",
            "(0, 0): ───@───@───\n",
            "           │   │\n",
            "(0, 1): ───@───┼───\n",
            "               │\n",
            "(0, 2): ───────@───\n",
            "\n",
            "Foxtail device:\n",
            "Not allowed. Non-local interaction: cirq.CZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)).\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xZ68bWEjoMKt",
        "colab_type": "text"
      },
      "source": [
        "## Simulation\n",
        "\n",
        "The results of the application of a quantum circuit can be calculated by a `Simulator`.  Cirq comes bundled with a simulator that can calculate the results of circuits up to about a limit of 20 qubits.  It can be initialized with `cirq.Simulator()`.\n",
        "\n",
        "There are two different approaches to using a simulator:\n",
        "\n",
        "*   `simulate()`:  Since we are classically simulating a circuit, a simulator can directly access and view the resulting wave function.  This is useful for debugging, learning, and understanding how circuits will function.  \n",
        "*   `run()`:  When using actual quantum devices, we can only access the end result of a computation and must sample the results to get a distribution of results.  Running the simulator as a sampler mimics this behavior and only returns bit strings as output.\n",
        "\n",
        "Let's try to simulate a 2-qubit \"Bell State\":"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "AwC4SL6CHpXm",
        "colab_type": "code",
        "outputId": "5339deec-7cad-4320-814e-b5dc6ae6eef9",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 119
        }
      },
      "source": [
        "# Create a circuit to generate a Bell State:\n",
        "# sqrt(2) * ( |00> + |11> )\n",
        "bell_circuit = cirq.Circuit()\n",
        "q0, q1 = cirq.LineQubit.range(2)\n",
        "bell_circuit.append(cirq.H(q0))\n",
        "bell_circuit.append(cirq.CNOT(q0,q1))\n",
        "\n",
        "# Initialize Simulator\n",
        "s=cirq.Simulator()\n",
        "\n",
        "print('Simulate the circuit:')\n",
        "results=s.simulate(bell_circuit)\n",
        "print(results)\n",
        "print()\n",
        "\n",
        "# For sampling, we need to add a measurement at the end\n",
        "bell_circuit.append(cirq.measure(q0, q1, key='result'))\n",
        "\n",
        "print('Sample the circuit:')\n",
        "samples=s.run(bell_circuit, repetitions=1000)\n",
        "# Print a histogram of results\n",
        "print(samples.histogram(key='result'))"
      ],
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Simulate the circuit:\n",
            "measurements: (no measurements)\n",
            "output vector: 0.707|00⟩ + 0.707|11⟩\n",
            "\n",
            "Sample the circuit:\n",
            "Counter({3: 537, 0: 463})\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "06Q_7vlQSu4Z",
        "colab_type": "text"
      },
      "source": [
        "### Using parameter sweeps\n",
        "\n",
        "Cirq circuits allow for gates to have symbols as free parameters within the circuit.  This is especially useful for variational algorithms, which vary parameters within the circuit in order to optimize a cost function, but it can be useful in a variety of circumstances.\n",
        "\n",
        "For parameters, cirq uses the library `sympy` to add `sympy.Symbol` as parameters to gates and operations.  \n",
        "\n",
        "Once the circuit is complete, you can fill in the possible values of each of these parameters with a `Sweep`.  There are several possibilities that can be used as a sweep:\n",
        "\n",
        "*   `cirq.Points`: A list of manually specified values for one specific symbol as a sequence of floats\n",
        "*   `cirq.Linspace`: A linear sweep from a starting value to an ending value.\n",
        "*   `cirq.ListSweep`: A list of manually specified values for several different symbols, specified as a list of dictionaries.\n",
        "*   `cirq.Zip` and `cirq.Product`: Sweeps can be combined list-wise by zipping them together or through their Cartesian product.\n",
        "\n",
        "A parameterized circuit and sweep together can be run using the simulator or other sampler by changing `run()` to `run_sweep()` and adding the sweep as a parameter.\n",
        "\n",
        "Here is an example of sweeping an exponent of a X gate:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ElyizofbLGq9",
        "colab_type": "code",
        "outputId": "860c31c6-0319-4b8e-d3fa-01f6848c3726",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 282
        }
      },
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import sympy\n",
        "\n",
        "# Perform an X gate with variable exponent\n",
        "q = cirq.GridQubit(1,1)\n",
        "circuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'),\n",
        "                       cirq.measure(q, key='m'))\n",
        "\n",
        "# Sweep exponent from zero (off) to one (on) and back to two (off)\n",
        "param_sweep = cirq.Linspace('t', start=0, stop=2, length=200)\n",
        "\n",
        "# Simulate the sweep\n",
        "s = cirq.Simulator()\n",
        "trials = s.run_sweep(circuit, param_sweep, repetitions=1000)\n",
        "\n",
        "# Plot all the results\n",
        "x_data = [trial.params['t'] for trial in trials]\n",
        "y_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials]\n",
        "plt.scatter('t','p', data={'t': x_data, 'p': y_data})\n"
      ],
      "execution_count": 63,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<matplotlib.collections.PathCollection at 0x7f54d6c1d320>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 63
        },
        {
          "output_type": "display_data",
          "data": {
            "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAD4CAYAAAD8Zh1EAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjEsIGh0\ndHA6Ly9tYXRwbG90bGliLm9yZy+j8jraAAAgAElEQVR4nO3dcZCc9X3f8fdXx2JOtsvJlTI1C1hi\nSkRRFHT2jUOtTGqIgzAp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gn4We/oC7l83sEmCfmR129x92qElfA77i7m+Z2b+k8unm6g69dhK3AM+4e3iz\n2G5er8wys6uoBPTfDD39m9Vr9SvAN8zs+9Xea6d8m8rv6+dW2dmsBFzawddv5Hpgv7uHe/NtvWZm\n9h4qf0Dudve/T+vnJpG1HnozG1JjZ29IneR729kuzOxjwOeBG9z9reB5dy9X//8K8E0qf7k70i53\n/2moLV8EPpT0e9vZrpBbqPk43MbrlUS9trfzejVkZr9O5fd3o7u/vQF76Fq9Afwv0kszJuLuf+/u\nP69+/TxQMLOVdPl6hcTdXyt6wSgAAAGvSURBVKlfMzMrUAnmT7r7sxGntPf+SntgoMVBhXOoDAas\n4Z2BlHU15/wbzh4U3VX9eh1nD4q+QnqDoknaNUxlEOjSmudXAO+qfr0S+FtSGhxK2K73h77+F8AB\nf2cQ5kfV9q2ofv2+TrWret5lVAaorBPXK/Qaq6k/yPe7nD1o9Tftvl4J2nQxlTGhj9Q8/27gvaGv\nvwVcm+a1StC2fxT8/qgExuPVa5foHmhXu6rHz6eSZ393J65Z9d/9ZeCxmHPaen+l+otP6aJcR2V0\n+IfA56vPbaPS6wU4D3i6eoP/DXBJ6Hs/X/2+o8DHO9yu/w38X2Cq+t/u6vMfAQ5Xb+jDwB0dbtfD\nwJHq678AXBb63j+oXsdjwO93sl3Vx1uB7TXf1+7r9RXgJ8A8lTzlHcAfA39cPW7A49V2HwZG2n29\nErTpi8DJ0L01UX3+kup1OlT9HX8+zWuVsG13he6vA4T+6ETdA51qV/Wc26kUSoS/r23XjEoqzIHv\nhH5X13Xy/tLUfxGRnMhaDl1ERJZIAV1EJCcU0EVEckIBXUQkJxTQRURyQgFdRCQnFNBFRHLi/wPY\nMkoH/CCWNgAAAABJRU5ErkJggg==\n",
            "text/plain": [
              "<Figure size 432x288 with 1 Axes>"
            ]
          },
          "metadata": {
            "tags": []
          }
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M8oLYwusz4XE",
        "colab_type": "text"
      },
      "source": [
        "## Unitary matrices and decompositions\n",
        "\n",
        "Most quantum operations have a unitary matrix representation.  This matrix can be accessed by applying `cirq.unitary()`.  This can be applied to gates, operations, and circuits that support this protocol and will return the unitary matrix that represents the object."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xn9nnBA70s23",
        "colab_type": "code",
        "outputId": "db800a4f-609e-41aa-ba8d-cdad21fadaed",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 238
        }
      },
      "source": [
        "print('Unitary of the X gate')\n",
        "print(cirq.unitary(cirq.X))\n",
        "\n",
        "print('Unitary of SWAP operator on two qubits.')\n",
        "q0, q1 = cirq.LineQubit.range(2)\n",
        "print(cirq.unitary(cirq.SWAP(q0, q1)))\n",
        "\n",
        "print('Unitary of a sample circuit')\n",
        "print(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1))))"
      ],
      "execution_count": 64,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Unitary of the X gate\n",
            "[[0.+0.j 1.+0.j]\n",
            " [1.+0.j 0.+0.j]]\n",
            "Unitary of SWAP operator on two qubits.\n",
            "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
            "Unitary of a sample circuit\n",
            "[[0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
            " [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
            " [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n",
            " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ls6Tnx90Y94Q",
        "colab_type": "text"
      },
      "source": [
        "### Decompositions \n",
        "\n",
        "Many gates can be decomposed into an equivalent circuit with simpler operations and gates.  This is called decomposition and can be accomplished with the `cirq.decompose` protocol.  \n",
        "\n",
        "For instance, a Hadamard H gate can be decomposed into X and Y gates:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "u8JwZaAUfbSv",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "ea971a0b-6265-4f03-8d6e-5220e8a1008c"
      },
      "source": [
        "print(cirq.decompose(cirq.H(cirq.LineQubit(0))))"
      ],
      "execution_count": 65,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[(cirq.Y**0.5).on(cirq.LineQubit(0)), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.LineQubit(0))]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B8ciZZSSf2jb",
        "colab_type": "text"
      },
      "source": [
        "Another example is the 3-qubit Toffoli gate, which is equivalent to a controlled-controlled-X gate.  Many devices do not support a three qubit gate, so it is important "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bbjRWlzjgPwf",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        },
        "outputId": "eeed11be-7865-4f4d-f74d-60a2d050c1e3"
      },
      "source": [
        "q0, q1, q2 = cirq.LineQubit.range(3)\n",
        "print(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2))))"
      ],
      "execution_count": 66,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "0: ───T────────────────@─────────────────────────────────@─────────────────────────────@────────────────────────────@───────────────────────────────────────\n",
            "                       │                                 │                             │                            │\n",
            "1: ───T───────Y^-0.5───@───Y^0.5────@───T^-1────Y^-0.5───@────────Y^0.5───@───Y^-0.5───@──────Y^0.5────@───Y^-0.5───@──────Y^0.5────@───────────────────────\n",
            "                                    │                                     │                            │                            │\n",
            "2: ───Y^0.5───X────────T───Y^-0.5───@───Y^0.5───T────────Y^-0.5───────────@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5───Y^0.5───X───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VWcik4ZwggXj",
        "colab_type": "text"
      },
      "source": [
        "The above decomposes the Toffoli into a simpler set of one-qubit gates and CZ gates at the cost of lengthening the circuit considerably.\n",
        "\n",
        "Some devices will automatically decompose gates that they do not support.  For instance, if we use the `Foxtail` device from above, we can see this in action by adding an unsupported SWAP gate:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "oS7vWnuHjLhE",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 68
        },
        "outputId": "2a50461b-374d-4a49-9145-31868314d05a"
      },
      "source": [
        "swap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1))\n",
        "print(cirq.Circuit(swap, device=cirq.google.Foxtail))"
      ],
      "execution_count": 67,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(0, 0): ───S^-1───Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───Z───\n",
            "                           │                          │                   │\n",
            "(0, 1): ───Z──────Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───S───\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rIUbvdVQkHbX",
        "colab_type": "text"
      },
      "source": [
        "### Optimizers\n",
        "\n",
        "The last concept in this tutorial is the optimizer.  An optimizer can take a circuit and modify it.  Usually, this will entail combining or modifying operations to make it more efficient and shorter, though an optimizer can, in theory, do any sort of circuit manipulation.\n",
        "\n",
        "For example, the `MergeSingleQubitGates` optimizer will take consecutive single-qubit operations and merge them into a single `PhasedXZ` operation."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5WvfOdaG5C_6",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 102
        },
        "outputId": "f06c8c8c-c597-4beb-edd9-badea86efc9d"
      },
      "source": [
        "q=cirq.GridQubit(1, 1)\n",
        "optimizer=cirq.MergeSingleQubitGates()\n",
        "c=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25)\n",
        "print(c)\n",
        "optimizer.optimize_circuit(c)\n",
        "print(c)"
      ],
      "execution_count": 68,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "(1, 1): ───X^0.25───Y^0.25───T───\n",
            "           ┌                           ┐\n",
            "(1, 1): ───│ 0.5  +0.707j -0.   -0.5j  │───────────\n",
            "           │ 0.354+0.354j  0.146+0.854j│\n",
            "           └                           ┘\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xRfQqzdx7lUI",
        "colab_type": "text"
      },
      "source": [
        "Other optimizers can assist in transforming a circuit into operations that are native operations on specific hardware devices.  You can find more about optimizers and how to create your own elsewhere in the documentation."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8QbTGmKlYT4i",
        "colab_type": "text"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "After completing this tutorial, you should be able to use gates and operations to construct your own quantum circuits, simulate them, and to use sweeps.  It should give you a brief idea of the commonly used \n",
        "\n",
        "There is much more to learn and try out for those who are interested:\n",
        "\n",
        "* Learn about the variety of [Gates](gates.ipynb) available in cirq and more about the different ways to construct [Circuits](circuits.ipynb)\n",
        "* Learn more about [Simulations](simulation.ipynb) and how it works.\n",
        "* Learn about [Noise](noise.ipynb) and how to utilize multi-level systems using [Qudits](qudits.ipynb)\n",
        "* Dive into some [Examples](examples.md) and some in-depth tutorials of how to use cirq.\n",
        "\n",
        "Also, join our [cirq-announce mailing list](https://groups.google.com/forum/#!forum/cirq-announce) to hear about changes and releases or go to the [cirq github](https://github.com/quantumlib/Cirq/) to file issues."
      ]
    }
  ]
}
